package com.imist.code;




import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CaptcahCode {

    public static  String  drawImage(HttpServletResponse response){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            builder.append(randomChar());
        }
        String code = builder.toString();
        //定义图片的宽度和高度
        int width = 125;
        int heign = 25;
        //创建图片缓冲流
        BufferedImage bufferedImage = new BufferedImage(width,heign,BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics2D = bufferedImage.createGraphics();
        Font font = new Font("微软雅黑",Font.PLAIN,20);
        Color color = new Color(0,0,0);
        graphics2D.setColor(color);
        graphics2D.setFont(font);
        graphics2D.setBackground(new Color(226,226,240));
        graphics2D.clearRect(0,0,width,heign);
        //绘制形状
        FontRenderContext context = graphics2D.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code,context);

        //计算文件的坐标和间距
        double x = (width - bounds.getWidth())/2;
        double y = (heign - bounds.getHeight())/2;

        double ascent = bounds.getY();
        double baseY = y - ascent;
        graphics2D.drawString(code,(int) x,(int) baseY);

        //结束绘制
        graphics2D.dispose();
        try {
            ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  code;
    }

    private static char randomChar(){
        String string = "QWERTYUIOPASDFGHJKLMNBVCXZ123456789";
        Random random = new Random();
        char c = string.charAt(random.nextInt(string.length()));
        return c;
    }

    public static void main(String[] args) {
        System.out.println(drawImage(null));
    }
}
